import { defineConfig } from "vite";
import react from "@vitejs/plugin-react-swc";
import legacy from "@vitejs/plugin-legacy";

const CORRECT_API_TARGET = 'http://47.121.193.239:9800';

console.log('🚀 Vite 代理配置: API请求将被代理到', CORRECT_API_TARGET);

// https://vitejs.dev/config/
export default defineConfig({
  define: {
    // 确保全局变量在构建时正确处理
    global: 'globalThis',
  },
  server: {
    host: "0.0.0.0",
    port: 9800,
    proxy: {
      '/api': {
        target: CORRECT_API_TARGET,
        changeOrigin: true,
        secure: false,
        rewrite: (path) => path,
        configure: (proxy, _options) => {
          proxy.on('error', (err, _req, _res) => {
            console.log('🚨 代理错误:', err);
          });
          proxy.on('proxyReq', (proxyReq, req, _res) => {
            console.log('📡 代理请求:', req.method, req.url, '->', proxyReq.getHeader('host') + proxyReq.path);
          });
          proxy.on('proxyRes', (proxyRes, req, _res) => {
            console.log('📡 代理响应:', proxyRes.statusCode, req.url);
          });
        }
      }
    },
    cors: true
  },
  plugins: [
    react(),
    legacy({
      targets: ["chrome 52"],
      additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
      renderLegacyChunks: true,
      modernPolyfills: true,
    }),
  ],
  build: {
    rollupOptions: {
      // 确保 js-cookie 被正确外部化或内联
      external: [],
      output: {
        globals: {
          'js-cookie': 'Cookies'
        }
      }
    },
  },
});
